package com.zy.ipanalysis.service;

import com.zy.ipanalysis.dao.IpDao;
import com.zy.ipanalysis.dao.IspDao;
import com.zy.ipanalysis.dao.IspMaskDao;
import com.zy.ipanalysis.model.Ip;
import com.zy.ipanalysis.model.IspMask;
import com.zy.commom.utils.IpUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by ZYDR on 2015/12/26.
 */
@Service
public class IpService {

    @Autowired
    IpDao ipDao;
    @Autowired
    IspMaskDao ispMaskDao;
    @Autowired
    IspDao ispDao;
    public Ip queryForId(int id){
        return  ipDao.queryForId(id);
    }
    public void insert(Ip ip){
        ipDao.insert(ip);
    }
    public List<Integer> queryForAll(){
        return ipDao.queryForAll();
    }
    public List<Integer> queryWithRange(int startIndex,int endIndex){
        return  ipDao.queryWithRange(startIndex,endIndex);
    }
    public void updateIpTimesByVolume(HashMap<Integer,Integer> ip_times){
        List<Ip> list=new ArrayList<Ip>();
        for (int id:ip_times.keySet()){
            Ip ip=new Ip();
            ip.setId(id);
            ip.setTimes(ip_times.get(id));
            list.add(ip);
        }
        ipDao.updateIpTimesByVolume(list);
    }
    /**
     *
     * @param ipId
     * @param ispId 为-1时不修改
     * @param districtId 为-1时不修改
     */
    public void updateIpInfo(int ipId,int ispId,int districtId){
        ipDao.updateIpInfo(ipId,ispId,districtId);
    }
    public int getNumberByIspId(int ispId){
        return ipDao.getNumberByIspId(ispId);
    }
    public int count(){
        return  ipDao.count();
    }
    public void insertByVolume(List<Ip> ipList){
        ipDao.insertByVolume(ipList);
    }

    /**
     * 获得某一运营商的
     * @param ispId -1时代表所有
     * @return
     */
    public int getFlowByIspId(@Param("ispId") int ispId){
        return  ipDao.getFlowByIspId(ispId);
    }
    public String queryIspByIp(String ip){
        int ipV= IpUtil.ip2Int(ip);
        int[] masks=new int[17];
        for(int i=0;i<=16;i++){
            masks[i]=-1<<(i+8);
        }
        int count=0;
        for(int mask:masks){
            IspMask ispMask=ispMaskDao.queryByNetId(mask&ipV);
            if (ispMask!=null&&ispMask.getMask()==mask){
                return ispDao.getIspName(ispMask.getIspId());
            }
        }
        return "未知运营商";
    }
}
